<template>
  <div id="container" ref="container">
    <el-table
      :data="tableData"
      :header-cell-style="headClass"
      :cell-style="tableClass"
      style="width: 100%"
    >
      <el-table-column fixed="left" prop="name" label="姓名" width="100"></el-table-column>
      <el-table-column prop="mobile" label="手机号码" min-width="130"></el-table-column>
      <el-table-column prop="username" label="登录名(学号)" min-width="110"></el-table-column>
      <el-table-column prop="power" label="负责模块" min-width="150"></el-table-column>
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEditYes(scope.$index,scope.row)">修改</el-button>
          <el-button type="text" size="small" @click="handleEditNo(scope.$index,scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align:right;margin-top:6px;">
      <el-button type="primary" @click="dialogFormVisible=true,operation='add'">新增+</el-button>
    </div>
    <!------------------------弹出框------------------------------>
    <el-dialog
      title="填写信息"
      :visible.sync="dialogFormVisible"
      center
      @close="notSubmit('okForm')"
      :width="diaWidth"
    >
      <el-form
        style="padding:0 20px;"
        label-width="auto"
        :rules="rules"
        label-position="left"
        :model="okForm"
        ref="okForm"
      >
        <el-form-item v-if="operation !== 'update'" label="登录名(学号)" prop="username">
          <el-input
            v-model="okForm.username"
            onkeyup="this.value=this.value.replace(/^\s+|\s+$/g,'')"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            placeholder="请输入密码"
            v-model="okForm.password"
            show-password
            onkeyup="this.value=this.value.replace(/^\s+|\s+$/g,'')"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password2">
          <el-input
            placeholder="请再次输入密码"
            v-model="okForm.password2"
            show-password
            onkeyup="this.value=this.value.replace(/^\s+|\s+$/g,'')"
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="okForm.name" onkeyup="this.value=this.value.replace(/^\s+|\s+$/g,'')"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="okForm.phone" onkeyup="this.value=this.value.replace(/^\s+|\s+$/g,'')"></el-input>
        </el-form-item>
        <el-form-item label="负责模块" prop="module">
          <el-select
            v-model="okForm.module"
            placeholder="请选择模块"
            style="-webkit-tap-highlight-color: transparent;"
          >
            <el-option label="1:基本维修" value="1"></el-option>
            <el-option label="2:基本维修+文章管理" value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item id="buttonbox" style="text-align:center;">
          <el-button @click="notSubmit('okForm')">取消</el-button>
          <el-button type="primary" @click="okSubmit('okForm')">确认</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 密码
    var validateNumber = (rule, value, callback) => {
      if (this.okForm.password.trim() == "") {
        callback(new Error("请输入密码"));
      } else if (this.okForm.password.trim().toString().length < 6) {
        callback(new Error("密码长度应在6位数以上"));
      } else {
        callback();
      }
    };
    // 确认密码
    var validateNumber1 = (rule, value, callback) => {
      if (this.okForm.password2.trim() == "") {
        callback(new Error("请再次输入密码"));
      } else if (this.okForm.password2 !== this.okForm.password) {
        callback(new Error("密码输入不一致"));
      } else {
        callback();
      }
    };
    //验证用户名
    // var validateNumber2 = (rule, value, callback) => {
    //   if (this.okForm.username.trim() == "") {
    //     callback(new Error("请输入用户名"));
    //   } else if (this.okForm.username.trim().toString().length > 12) {
    //     callback(new Error("用户名过长"));
    //   } else if (this.okForm.username.trim().toString().length < 6) {
    //     callback(new Error("用户名过短"));
    //   } else {
    //     callback();
    //   }
    // };
    //验证数字
    var validateNumber2 = (rule, value, callback) => {
      if (this.okForm.username.trim() == "" || isNaN(this.okForm.username)) {
        callback(new Error("请输入正确的学号"));
      } else if (this.okForm.username.trim().toString().length !== 11) {
        callback(new Error("学号长度应为11位,且不能含有空格"));
      } else {
        callback();
      }
    };
    //手机号
    var validateNumber3 = (rule, value, callback) => {
      const reg = /^1([38]\d|5[0-35-9]|7[3678])\d{8}$/;
      if (!reg.test(value)) {
        callback(new Error("手机号格式错误"));
      } else {
        callback();
      }
    };
    return {
      dialogFormVisible: false,
      operation: "", //判断 add 或 update 操作
      diaWidth: document.body.clientWidth > 768 ? "500px" : "90%", //diaing弹出框宽度
      okForm: {
        id: "",
        username: "",
        password: "",
        password2: "",
        name: "",
        phone: "",
        module: ""
      }, //弹出框数据
      tableData: [], //人员列表
      rules: {
        username: [
          { required: true, validator: validateNumber2, trigger: "blur" }
        ],
        password: [
          { required: true, validator: validateNumber, trigger: "blur" }
        ],
        password2: [
          { required: true, validator: validateNumber1, trigger: "blur" }
        ],
        phone: [
          { required: true, validator: validateNumber3, trigger: "blur" }
        ],
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        module: [
          { required: true, message: "请选择负责模块", trigger: "change" }
        ]
      }
    };
  },
  mounted() {
    this.getPerlist();
  },
  methods: {
    //获取人员列表
    getPerlist() {
      this.$axios
        .get("/api/manage/user/queryList")
        .then(res => {
          res.data.data.userList.forEach(item => {
            if (item.power == 0) {
              item.power = "账号关闭";
            } else if (item.power == 1) {
              item.power = "1:基本维修";
            } else if (item.power == 2) {
              item.power = "2:基本维修+文章管理";
            } else if (item.power > 2) {
              item.power = "老师";
            }
          });
          this.tableData = res.data.data.userList;
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 表头样式设置
    headClass() {
      return "text-align: center;";
    },
    // 单元格样式
    tableClass() {
      return "text-align: center;";
    },
    setInput(mail) {
      this.inputEmail = mail;
    },
    //操作事件 修改
    handleEditYes(index, row) {
      this.operation = "update";
      this.$axios
        .get(
          "/api/manage/user/query/" +
            row.username
        )
        .then(res => {
          if (res.data.code == 200) {
            let user = res.data.data.user;
            this.okForm.id = user.id;
            this.okForm.username = user.username;
            this.okForm.password = user.password;
            this.okForm.password2 = user.password;
            this.okForm.name = user.name;
            this.okForm.phone = user.mobile;
            // if(user.power==1){
            //   this.okForm.module = "基本维修";
            // }else if(user.power==2){
            //   this.okForm.module = "基本维修+文章管理";
            // }
            this.okForm.module = user.power;
            this.dialogFormVisible = true;
          }
        });
    },
    // 删除
    handleEditNo(index, row) {
      this.$confirm("确定要 删除 吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      }).then(() => {
        this.$axios
          .get(
            "/api/manage/user/deleteById/" +
              row.id
          )
          .then(res => {
            if (res.data.code == 200) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.tableData.splice(index, 1);
            }
          })
          .catch(err => {
            this.$alert("删除失败,请稍后重试!", {
              confirmButtonText: "确定",
              center: true
            });
          });
      });
    },
    //确认信息
    okSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let PramsData = {
            id: this.okForm.id,
            password: this.okForm.password,
            power: this.okForm.module,
            name: this.okForm.name,
            mobile: this.okForm.phone
          };
          if (this.operation !== "update") {
            PramsData.username = this.okForm.username;
          }
          if (this.operation == "add") {
            this.$axios
              .post(
                "/api/manage/user/add?",
                PramsData
              )
              .then(res => {
                if (res.data.code == 200) {
                  this.dialogFormVisible = false;
                  this.$refs[formName].resetFields();
                  this.$alert("新增成功!", {
                    confirmButtonText: "确定",
                    center: true
                  });
                  this.getPerlist();
                } else {
                  this.$alert("新增失败：" + res.data.data.message, {
                    confirmButtonText: "确定",
                    center: true
                  });
                }
              })
              .catch(err => {
                this.$alert("网络异常,请稍后再试!", {
                  confirmButtonText: "确定",
                  center: true
                });
              });
          } else if (this.operation == "update") {
            this.$axios
              .post(
                "/api/manage/user/update",
                PramsData
              )
              .then(res => {
                if (res.data.code == 200) {
                  this.dialogFormVisible = false;
                  this.$refs[formName].resetFields();
                  this.$alert("修改成功!", {
                    confirmButtonText: "确定",
                    center: true
                  });
                  this.getPerlist();
                } else {
                  this.$alert("修改失败：" + res.data.data.message, {
                    confirmButtonText: "确定",
                    center: true
                  });
                }
              })
              .catch(err => {
                this.$alert("网络异常,请稍后再试!", {
                  confirmButtonText: "确定",
                  center: true
                });
              });
          }
        } else {
          return false;
        }
      });
    },
    //取消按钮
    notSubmit(formName) {
      this.dialogFormVisible = false;
      this.$refs["okForm"].resetFields();
      this.okForm = {
        id: "",
        username: "",
        password: "",
        password2: "",
        name: "",
        phone: "",
        module: ""
      };
    }
  }
};
</script>
<style lang="scss" scoped>
.container{
  #buttonbox{
    /deep/ .el-form-item__content{
      margin-left: 0!important;
    }
  }
}
</style>